﻿using AutoMapper;
using Blog.Core.Domain.Model.User;
using Blog.Core.DTO;
using Blog.Core.DTO.ViewModel;
using Blog.Core.DTO.ViewModel.User;
using Blog.Core.IRepositories;
using Blog.Core.IRepositories.IUser;
using Blog.Core.IServices.IUser;
using Blog.Core.Repositories.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
namespace Blog.Core.Services.User
{
    /// <summary>
    /// 角色信息服务
    /// </summary>
    public class RolesPermissionService : BaseService<RolePermission>, IRolesPermissionService
    {
        private readonly IRolePermissionRepository _rolePermissionRepository;
        private readonly IMapper mapper;
        private readonly IUnOfWork unOfWork;
        private readonly IPermissionsRepository permissionsRepository;

        public RolesPermissionService(IRepository<RolePermission> repository, IUnOfWork unOfWork, IRolePermissionRepository rolePermissionRepository, IMapper mapper, IPermissionsRepository permissionsRepository) : base(repository, unOfWork)
        {
            _rolePermissionRepository = rolePermissionRepository;
            this.mapper = mapper;
            this.unOfWork = unOfWork;
            this.permissionsRepository = permissionsRepository;
        }
        /// <summary>
        /// 角色添加权限
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> RolePermission(RequestRolePermissionDTO entity)
        {
            //获取所有用户权限关系
            var list= await _rolePermissionRepository.GetAll();
            ///查询角色之前的权限
            var m = list.Where(x => x.RoleId.Equals(entity.RoleId));
            foreach (var item in m)
            {
                //删除角色之前的权限
                await _rolePermissionRepository.Delete(item.Id);
            }
            //角色权限id
            string[] ids = entity.PermissionId.Split(',');
            ids.ToList().ForEach(x =>
            {
                var m = new RolePermission
                {
                    RoleId = entity.RoleId,
                    PermissionId = Convert.ToInt32(x)
                };
                _rolePermissionRepository.Add(m);
            });
            return await unOfWork.SaveChanges();
        }
        /// <summary>
        /// 角色权限的反填
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public async Task<dynamic> GetRolePermission(int roleid)
        {
            var list = await _rolePermissionRepository.GetAll();
            var m = list.DistinctBy(x => x.RoleId).ToList().Where(x=>x.RoleId==roleid);
            var entity = from y in m
                         select new
                         {
                             RoleId = y.RoleId,
                             PermissId = list.Where(z=>z.RoleId==y.RoleId).Select(x=>x.PermissionId)
                         };
           return entity;

        }
        //角色权限的修改
        public async Task<dynamic> UpdatePermission(RequestRolePermissionDTO model)
        {
            var tran = unOfWork.GetDbContext().Database.BeginTransaction();//开启事务
            ResponseResultDTO<dynamic> result = new ResponseResultDTO<dynamic>();
            try
            {
                //先删后加
                var list = await _rolePermissionRepository.GetAll();
                var m = list.Where(x => x.RoleId == model.RoleId).Select(x => x.Id).ToList();
                m.ForEach(async x =>
                {
                    await _rolePermissionRepository.Delete(x);
                });
                //添加角色
                //角色权限id
                string[] ids = model.PermissionId.Split(',');
                ids.ToList().ForEach(x =>
                {
                    var role = new RolePermission
                    {
                        RoleId = model.RoleId,
                        PermissionId = Convert.ToInt32(x)
                    };
                    _rolePermissionRepository.Add(role);
                });
                tran.Commit();//事务提交
                await unOfWork.SaveChanges();//影响到数据库
                result.Code = ResultStatusCode.SUCCESS;
                result.Message = "操作成功";
                return result;
            }
            catch (Exception)
            {
                tran.Rollback();//事务回滚
                result.Code = ResultStatusCode.HANDLEFAIL;
                result.Message = "操作失败";
                return result;
                //throw;
            }
           

        }
    }
}
